package com.example.testgit.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.testgit.entity.StudentDO;
import com.example.testgit.mapper.StudentMapper;

import java.util.List;

/**
 * @author: lyh
 * @create: 2023/5/9 19:20
 * Description：
 */
public class StudentDOListener implements ReadListener<StudentDO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10;
    /**
     * 缓存的数据
     */
    private List<StudentDO> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private StudentMapper studentMapper;

    public StudentDOListener() {
    }

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     */
    public StudentDOListener(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }


    @Override
    public void invoke(StudentDO studentDO, AnalysisContext analysisContext) {
        System.out.println(JSON.toJSONString(studentDO));
        list.add(studentDO);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        studentMapper.insertBatch(list);
    }
}
